<%--
  Created by IntelliJ IDEA.
  User: zhf
  Date: 2021/2/8
  Time: 19:13
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="utf-8" %>
<%@taglib prefix="fix" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
  String path = request.getContextPath();
  String basePath = request.getScheme()+"://"
          +request.getServerName()+":"
          +request.getServerPort()
          +path+"/";
%>
<html>
<head>
  <base href="<%=basePath %>"/>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="cache-control" content="no-cache">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>主页</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"
        integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js"
          integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
          crossorigin="anonymous"></script>
  <link rel="stylesheet" href="css/base.css">
  <style type="text/css">
  </style>
</head>

<body>
<div class="container">
<%--  <form name="listForm" id="listForm" method="post" action="?">--%>
    <table class="table table-responsive">
      <caption>
        <h2>用户信息管理系统</h2>
      </caption>
      <caption>
        <button type="button" class="btn btn-info" id="user_add" data-toggle="modal" data-target="#myModal">注册</button>
        <button  class="btn btn-info" id="user_delete">删除</button>
        <button type="button" class="btn btn-info" id="user_edit" data-toggle="modal" data-target="#myModal">编辑</button>
        <button class="btn btn-info" id="user_find">查询</button>
        <input type="text" id="s_name" placeholder="按姓名查询" style="width: 130px;" name="queryName">
      </caption>
      <thead>
      <tr>
        <th>序号</th>
        <th>用户ID</th>
        <th>姓名</th>
        <th>密码</th>
        <th>手机号</th>
        <th>创建时间</th>
      </tr>
      </thead>
      <tbody id="tbody">

      </tbody>
    </table>
<%--  </form>--%>

</div>

<!-- 模态框（Modal） -->
<div class="modal fade" id="myModal" role="dialog" aria-labelledby="modalLabel" data-backdrop="static" aria-hidden="true">
  <div class="modal-dialog" id="modalDialog">
    <div class="modal-content">
      <div class="modal-header">
        <button class="close" data-dismiss="modal" aria-hidden="true" aria-label="Close">
          <span>&times;</span>
        </button>
        <h4 class="modal-title" id="modalLabel">
          新增用户
        </h4>
      </div>
<%--    <form action="?" method="post" id="insertOrUpdStudent" name="insertOrUpdStudent">--%>
      <div class="modal-body" id="modal-body">
        <input type="hidden"  id="m_code" name="uid">
        <label for="m_userName">用户名:</label>
        <input type="text" class="form-control" id="m_userName" name="username" placeholder="请输入姓名"  required="required">
        <label for="m_password">密码:</label>
        <input type="text" class="form-control" id="m_password" name="password" placeholder="请输入密码"  required="required">
        <label for="m_phone">手机号:</label>
        <input type="text" class="form-control" id="m_phone" name="phone" placeholder="请输入手机号"  required="required">
      </div>
      <div class="modal-footer">
        <button id="save" class="btn btn-primary" data-dismiss="modal">保存
        </button>
      </div>
<%--    </form>--%>

    </div><!-- /.modal-content -->
  </div><!-- /.modal -->
</div>

<!-- 这里需要引入相关的js，很重要，请记住 -->
<script type="text/javascript" src="./js/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="./jquery-ui-1.12.1/jquery-ui.min.js"></script>
<script type="text/javascript" src="./js/employeeManage.js"></script>
<script>
  $(function(){

    // initTable();
    $("#modalDialog").draggable();//为模态对话框添加拖拽
    $("#myModal").css("overflow", "hidden");//禁止模态对话框的半透明背景滚动

  });

  function findUser(){
    // let newusers = new Array();
    // var userNameLike = $(this).siblings("#s_name").val();
    // $("#listForm").attr("action", "getUserList");
    // $("#listForm").submit();
    let userNameLike = $("#s_name").val();
    $.ajax({
      type:"get",
      url:"/getUserList?username=" + userNameLike,
      async:true,
      dataType:"json",
      success: function(users){
        var html = "";
        var color = "warning";
        var flag = true;
        for (var i in users) {
          if (flag) {
            color = "info";
          } else {
            color = "warning";
          }
          html = html + "<tr class='" + color + "'><td style='width:80px;'><input type='checkbox' name='uid' value = '" + users[i].uid + "'></td><td id='uid'>"
                  + users[i].uid + "</td><td id='username'>"
                  + users[i].username + "</td><td id='password'>"
                  + users[i].password + "</td><td id='phone'>"
                  + users[i].phone + "</td><td id='createtime'>"
                  + users[i].createtime + "</td>"
                  + "</tr>";
          flag = flag ^ 1;
        }
        $("tbody").html(html);
      },
      error:function () {
        alert("查找失败！");
      }
    });
  }

  $(document).ready(findUser());

  // 查询用户
  $("#user_find").on("click", function(){
    findUser();
  });

  var operateType;                // 按钮的操作类型

  // 当点击添加按钮
  $("#user_add").on("click", function () {
    operateType = "add";
    // 重置文本框中的内容
    $("#m_code").val("");
    $("#m_userName").val("");
    $("#m_password").val("");
    $("#m_phone").val("");

    // 模态框的标题切换
    $("#modalLabel").text("新增用户");
    $(this).attr("data-toggle","modal");  // 启用模态框
    $(this).attr("data-target","#myModal"); // 启用模态框

  });


  //当点击修改按钮
  $("#user_edit").on("click", function () {
    operateType = "edit";
    $("#modalLabel").text("编辑用户");
  });

  $("#user_edit").on("click", function () {
    let i;
    let box;
    const checkboxs = $("input[type='checkbox']");

    // 校验勾选了几个复选框
    let checkCount = 0;
    for (i = 0; i < checkboxs.length; i++) {
      box = checkboxs[i];
      if(box.checked){
        checkCount++;
      }
    }
    if(checkCount <= 0 || checkCount > 1){
      alert("请选择且只能选择一个用户！");
      $(this).attr("data-toggle",null); // 禁用模态框
      $(this).attr("data-target",null); // 禁用模态框
      return;
    }

    let f = false;
    for (i = 0; i < checkboxs.length; i++) {
      box = checkboxs[i];
      if (box.checked) {
        f = true;
        $(this).attr("data-toggle","modal");  // 启用模态框
        $(this).attr("data-target","#myModal"); // 启用模态框
        box = $(box);
        const studentId = box.parent().siblings("#uid").text();
        // 获取表格中选中的用户的各项数据
        const name = box.parent().siblings("#username").text();
        const password = box.parent().siblings("#password").text();
        const phone = box.parent().siblings("#phone").text();
        // 选中用户的各项数据，放在模态框的相应input框中
        $("#m_code").val(studentId);
        $("#m_userName").val(name);
        $("#m_password").val(password);
        $("#m_phone").val(phone);

      }
    }
    if(!f){
      alert("请选择一个用户！");
      $(this).attr("data-toggle",null); // 禁用模态框
      $(this).attr("data-target",null); // 禁用模态框
    }
  });

  function checkEmpty(){
    if($("#m_userName").val().length == 0){
      alert("用户名必须填写！");
      return false;
    }
    if($("#m_password").val().length == 0){
      alert("密码必须填写！");
      return false;
    }
    if($("#m_phone").val().length == 0){
      alert("手机号必须填写！");
      return false;
    }
    return true;
  };

  //保存用户
  $("#save").on("click", function () {
    var isChecked = checkEmpty();
    if(isChecked == false){
      return false;
    }
    let mUid = $("#m_code").val();
    let mUserName = $("#m_userName").val();
    let mPassword = $("#m_password").val();
    let mPhone = $("#m_phone").val();
    if (operateType == "add") {
      // $("#insertOrUpdStudent").attr("action", "register");
      // $("#insertOrUpdStudent").submit();
      var dataAdd = {
        "username":mUserName,
        "password":mPassword,
        "phone":mPhone
      };
      var jsonData = JSON.stringify(dataAdd);
      $.ajax({
        type:"post",
        url:"/register",
        async:true,
        contentType : 'application/json',
        dataType:"json",
        data:jsonData,
        success: function(data){
          findUser();
        },
        error:function () {
          alert("新增失败！");
        }
      });
    } else if (operateType == "edit") {
      // $("#insertOrUpdStudent").attr("action", "userUpdate");
      // $("#insertOrUpdStudent").submit();
      var dataUpd = {
        "uid":mUid,
        "username":mUserName,
        "password":mPassword,
        "phone":mPhone
      };
      var jsonData = JSON.stringify(dataUpd);
      $.ajax({
        type:"post",
        url:"/userUpdate",
        async:true,
        contentType : 'application/json',
        dataType:"json",
        data:jsonData,
        success: function(data){
          findUser();
        },
        error:function () {
          alert("修改失败！");
        }
      });
    }
  });

  $("#user_delete").on("click", function () {
    const checkboxs = $("input[type='checkbox']");  // 获取所有复选框
    let f = false;  // 是否选中用户的标记
    var idDeleteList = [];
    for (let i = 0; i < checkboxs.length; i++) {
      let box = checkboxs[i];
      if (box.checked) {  // 某个复选框被选中
        f = true;  // 标记 有 复选框被选中
        box = $(box); // jsdom对象转换成jquery对象
        let id = box.parent().siblings("#uid").text(); // 复选框父级的兄弟#code元素
        idDeleteList.push(id);
      }
    }
    if(!f){
      alert("请至少选择一个用户！");
    }
    else {
      // $("#listForm").attr("action", "studentDelete");
      // $("#listForm").submit();
      $.ajax({
        type: "get",
        url: "/deleteUserByUid?uid=" + idDeleteList[0],
        async: true,
        dataType: "json",
        success: function (data) {
          findUser();
        }
      });
    }

  });

</script>

</body>
</html>
